<!--  -->
<template>
  <div class='article-wrap'>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
      <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      v-model:error="error"
      error-text="请求失败，点击重新加载"
      >
       <article-item v-for="(article,index) in list"
         :key="index" :articles="article"
       ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from './articleItem.vue'
export default {
  components: {
    ArticleItem
  },
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      timestamp: null,
      error: false
    }
  },
  methods: {
    // 上拉自动调用此函数
    async onLoad () {
      try {
        const res = await getArticles({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now(), // 时间戳，首次请求设置为Date.now（）
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   JSON.parse('asddasdas')
        // }
        this.list.push(...res.data.data.results)
        // console.log(res)
        // 运行onLoad函数自动把loading设置为true
        // 加载此次数据完毕后要把loading设置为false
        // 下拉请求数据返回完毕 将refreshing设置为false，即上拉刷新完毕
        this.refreshing = false
        this.loading = false
        // 如果此次请求返回的数据长度部位空，即还存在数据
        if (res.data.data.results.length) {
          this.timestamp = res.data.data.pre_timestamp
        } else {
          this.finished = true // 没有更多数据了
        }
      } catch (error) {
        // 加载失败，显示失败提示
        this.error = true
        // 加载失败，要把loading图标关闭
        this.loading = false
      }
    },
    // 下拉自动调用此函数并且将refreshing设置为true
    onRefresh () {
      // 清空列表数据
      this.list = []
      // 刷新传递的timestamp要为最新的时间戳即Date.now()
      this.timestamp = null
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    }
  }
}
</script>

<style  scoped>
.article-wrap {
  height: 79vh ;
  overflow-y: auto;
}
</style>
